package com.inifitness.common.tools;

import java.io.IOException;

import jakarta.servlet.http.HttpServletResponse;

import com.inifitness.common.result.Result;
import com.inifitness.common.result.ResultCode;

import cn.hutool.json.JSONUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

/**
 * 响应报文写入工具类
 *
 * @author sunjinfeng
 * @version 1.0.0
 * @since 2024/04/18 11:00:00
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ResponseUtils {

  /**
   * 异常消息返回(适用过滤器中处理异常响应)
   *
   * @param response
   * @param resultCode
   */
  public static void writeErrMsg(HttpServletResponse response, ResultCode resultCode)
      throws IOException {
    switch (resultCode) {
      case ACCESS_UNAUTHORIZED, TOKEN_INVALID:
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        break;
      case TOKEN_ACCESS_FORBIDDEN:
        response.setStatus(HttpStatus.FORBIDDEN.value());
        break;
      default:
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        break;
    }
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setCharacterEncoding("UTF-8");
    response.getWriter().print(JSONUtil.toJsonStr(Result.failed(resultCode)));
  }


}
